#pragma once

#include <string>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

#define PATH "."
#define FILENAME "fifo"

// 创建管道
class NamedPipe
{
public:
    NamedPipe(const char *path, const char *filename)
        : _path(path), _filename(filename)
    {
        _pathname = (_path + '/' + _filename);
        int ret = mkfifo(_pathname.c_str(), 0666);
        if (ret < 0)
        {
            std::cerr << "mkfifo failed" << std::endl;
            exit(1);
        }
        std::cout << "mkfifo success……" << std::endl;
    }

    ~NamedPipe()
    {
        unlink(_pathname.c_str());
        std::cout << "unlink……" << std::endl;
    }

private:
    std::string _path;
    std::string _filename;
    std::string _pathname;
};

// 文件通信
class FifoComm
{
public:
    FifoComm(const char *path, const char *filename)
        : _path(path), _filename(filename)
    {
        _pathname = (_path + '/' + _filename);
    }
    void Write()
    {
        _fd = open(_pathname.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            std::cerr << "open failed" << std::endl;
            exit(1);
        }
        std::cout << "write open success……" << std::endl;
        while (true)
        {
            std::string str;
            std::getline(std::cin, str);
            if (str == "end") // client end!!!
                break;
            int ret = write(_fd, str.c_str(), str.size());
            if (ret < 0)
            {
                std::cerr << "write failed" << std::endl;
                exit(1);
            }
        }
    }
    void Read()
    {
        // 打开时, write 方没有执行open的时候，read方，就要在open内部进行阻塞
        // 直到有人把管道文件打开了，open才会返回
        _fd = open(_pathname.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            std::cerr << "open failed" << std::endl;
            exit(1);
        }
        std::cout << "read open success……" << std::endl;
        int cnt = 0;
        while (true)
        {
            char buff[1024];
            int n = read(_fd, buff, sizeof(buff) - 1);
            if (n > 0)
            {
                buff[n] = 0;
                std::cout << "client[" << cnt++ << "] say: " << buff << std::endl;
            }
            else if (n == 0)
            {
                std::cout << "write close -> read close" << std::endl;
                break;
            }
            else
            {
                std::cerr << "read failed" << std::endl;
                break;
            }
        }
    }
    void Close()
    {
        int ret = close(_fd);
        if (ret < 0)
        {
            std::cerr << "close failed" << std::endl;
            exit(1);
        }
        std::cout << "close success……" << std::endl;
    }
    ~FifoComm()
    {
    }

private:
    std::string _path;
    std::string _filename;
    std::string _pathname;
    int _fd = -1;
};